package com.gw.yunke.utils;

import java.io.*;

public class VideoUtil {

    /**
     * 生成截图
     * @param path 视频存储位置
     * @param imagePath 截图存储位置
     * @throws IOException
     */
    public static void captureImage(String path,String imagePath) throws IOException {

        Runtime runtime = Runtime.getRuntime();
        String cmd = "ffmpeg -i "+path+" -y -f image2 -ss 1 -t 0.001 -s 350x240 "+imagePath+"\n";

        Process process = runtime.exec("cmd");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
        bw.write(cmd);
        bw.flush();

        bw.close();

    }

    /**
     * 获取视频时长
     * @param path
     * @return
     * @throws IOException
     */
    public static String getVideoTime(String path) throws IOException {

        Runtime runtime = Runtime.getRuntime();
        //TODO:换成获取时长的命令
        String cmd = "ffmpeg -i "+ path + " 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//" +"\r\n" + "exit\r\n";


        Process process = runtime.exec("cmd");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        bw.write(cmd);
        bw.flush();

        StringBuffer stringBuffer = new StringBuffer();
        String line = null;
        while((line = br.readLine()) != null){
            if(line.contains(":") && !line.contains("/") && !line.contains("\\"))
                stringBuffer.append(line);
        }

        bw.close();
        br.close();

        return stringBuffer.toString();

    }

    public static void main(String args[]) throws IOException {
        System.out.println(getVideoTime("E:/1-1.mp4"));
    }


}
